<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@taglib prefix="shiro" uri="http://shiro.apache.org/tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<jsp:include page="/common/commonCss.jsp"/>
<jsp:include page="/common/commonJs.jsp"/>
 <script src="${basePath}commonJs/jquery.ztree.all.js"></script>
 <script type="text/javascript" src="${basePath}commonJs/ajaxfileupload.js"></script>
<title>嘉童游乐中心-商品出库清单</title>
<SCRIPT type="text/javascript">
		var selectNode=null;
		var treeNodes=[];
		//选中的商品
		var selectPrds=[];
		//只允许查询存在库存的商品
		var resverseTypes=[6,61];
		var resverseTypesVal=[6,61];
		//商品id
		var excludeId=[];
		var index = 0;
		var setting = {
			data: {
				simpleData: {
					enable: true
				}
			},
			callback:{
				onClick:zTreeOnClick
			}
		};

		 $(document).ready(function(){
			getTreeData();
			$("#resverseTypes").val(resverseTypesVal.join());
			$("#resverseTypes2").val(resverseTypesVal.join());
			$.fn.zTree.init($("#sptree"), setting, treeNodes);
			setDefaultForTree();
		}); 
		
		//设置ztrre默认选中,以及样式
		function setDefaultForTree(){
			$("#sptree_1_a").addClass("curSelectedNode");
			selectNode=treeNodes[0];
		}
			
		function zTreeOnClick(event, treeId, treeNode) {
			selectNode = treeNode;// 每次点击赋值 
			//点击根节点，显示所有商品*临时修改代码未优化*
			if(selectNode.getParentNode() == null)
			{
				var selectId=[];
				selectId = getSelectIds(selectId,treeNode);
				$("#selectId").val(selectId.join());
				select1("goodsOutForm");
			}
			else
			{
				$("#sptree_1_a").removeClass("curSelectedNode");
				//选中的商品id
				var selectId=[];
				selectId = getSelectIds(selectId,treeNode);
				$("#selectId").val(selectId.join());
				select1("goodsOutForm");
			}
		};
		
		//嵌套循环获得被选中商品及其子类商品的id
		function getSelectIds(selectId, treeNode) {
		selectId.push(treeNode.id);
		if (treeNode.isParent) {
			for ( var obj in treeNode.children) {
				getSelectIds(selectId, treeNode.children[obj]);
			}
		}
		return selectId;
		}

	/*获得商品分类的信息*/
	function getTreeData() {
		$.ajax({
			url : "${basePath}scmInvocing/productInfo/findCategoryList.shtml",
			data:{"resverseTypes":resverseTypes.join()},
			dataType : "json",
			type : "post",
			async : false,
			success : function(result) {
				var node;
				$(result).each(function(id, item) {
					if (id == 0) {
						node = {
							id : item.pkPrdcateId,
							pId : item.fkParPrdcateId,
							name : item.cateName,
							open : true,
							reserveFlag : item.reserveFlag,
							resverseType : item.resverseType
						};
					} else {
						node = {
							id : item.pkPrdcateId,
							pId : item.fkParPrdcateId,
							name : item.cateName,
							reserveFlag : item.reserveFlag,
							resverseType : item.resverseType
						};
					}
					treeNodes.push(node);
				});
			},
			error : function(XMLHttpRequest) {
				ajaxError(XMLHttpRequest);
			}
		});
	}

	function initTable(formId) {//库存查询分页显示
		var prdIdValue = $.trim($("#pkPrdIdValue").val());
		$("#pkPrdId").val(prdIdValue);
		var prdName = $.trim($("#prdNameValue").val());
		$("#prdName").val(prdName);

		var prdIdValue = $.trim($("#pkPrdIdValue").val());
		$("#pkPrdId2").val(prdIdValue);
		var prdName = $.trim($("#prdNameValue").val());
		$("#prdName2").val(prdName);

		var form = $("#" + formId);
		var pagenbean = new PageBean(form);
		pagenbean.setTableId("goodsOutTable");
		pagenbean.setCallback(callback);
		pagenbean.setFootId("goodsOutFoot");
		setPagebeanObj(pagenbean);
		pagenbean.doPage();
	}

	function callback(data) {
		if (data == null) 
		{
			return;
		}
		trimJsonArray(data);
		$.each(data,function(ind, obj) {
			var i = ind + 1;
			var htm = "<tr>";
			var num = (obj.stgCnt == "" ? 0 : obj.stgCnt);
			var storNum = obj.minStorage;
			if (storNum != null && storNum > num) {
				htm = "<tr class=\"bg_red\">";
			}
			htm += "<td><input name='chkItem' type='checkbox' value='"+obj.pkPrdId+"'/></td>";
			htm += "<td>" + i + "</td>";
			htm += "<td>" + obj.pkPrdId + "</td>";
			htm += "<td name='prdName'>"+ obj.prdName + "</td>";
			htm += "<td name='cateName'>"+ obj.cateName + "</td>";
			htm += "<td name='prdSpec'>"+ obj.prdSpec + "</td>";
			htm += "<td name='unitName'>" + obj.unitName + "</td>";
			htm += "<td name='stgCnt'>" + num + "</td></tr>";

			$("#goodsOutTable").find("tr:eq(" + ind + ")")
					.after(htm);
		});
			doChecked($("#selectAll"));
	}

	//设置pageNo为1
	function select1(formId) {
		$("#" + formId + " input:hidden[name='pageNo']").val(1);
		initTable(formId);
	}

	//上传附件
	function uploadAttachFile() {
		if ($("#ui-upload-input").val() == '') {
			alertError("请在上传前先选择文件");
			return false;
		}
		$.ajaxFileUpload({
			url : '${basePath}StockGoodsIn/uploadFile.shtml',
			secureuri : false, //是否启用安全提交,默认为false 
			fileElementId : 'ui-upload-input', //文件选择框的id属性
			dataType : 'text', //服务器返回的格式,可以是json或xml等
			success : function(data) { //服务器响应成功时的处理函数
				data = decodeURI(data);
				if (data != "") {
					alertInfo("出库单附件上传成功");
					$("#fkAttFile").val(data);

				} else {
					alertError("上传失败，请重试！");
					$("#fkAttFile").val("");
				}
			},
			error : function(data, status, e) { //服务器响应失败时的处理函数
				alertError("上传失败，请重试！");
				$("#fkAttFile").val("");
			}
		});
	}

	//上传
	function fileName() {
		var fileName = $("#ui-upload-input").val();
		if (fileName.lastIndexOf("\\") != -1) {
			fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
		}
		$("#ui-upload-filepathtxt").val(fileName);
	}
	
	function doChecked(o){
		$("[name = chkItem]:checkbox").attr("checked", o.attr("checked") == 'checked');
	}

	//新增出货商品全选、全不选
	$(function() {
		$("#selectAll").bind("click", function() {
			doChecked($(this));
		});

		//获取选中商品信息
		$("#addGoods").bind(
				"click",
				function() {
					initSelectPrds();
					var pkPrdId;
					var cateName;
					var prdSpec;
					var unitName;
					var stgCnt;
					var len = $("[name = chkItem]:checked").length;
					if (len == 0) {
						alertInfo("未选择出库商品");
						return;
					}
					$("[name = chkItem]:checked").each(
						function() {
							tr = $(this).parent().parent();
							pkPrdId = $(this).val();
							prdName = $(tr).find("td:[name='prdName']").html();
							cateName = $(tr).find("td:[name='cateName']").html();
							prdSpec = $(tr).find("td:[name='prdSpec']").html();
							unitName = $(tr).find("td:[name='unitName']").html();
							stgCnt = $(tr).find("td:[name='stgCnt']").html();
							selectPrds.push(pkPrdId + " _" + prdName + "_"
									+ cateName + "_" + prdSpec + "_"
									+ unitName + "_" + stgCnt);
							excludeId.push(pkPrdId);
						});
					$('#addSelectGoods').window('close');
					showSelectProduct();
					$("#selectAll").attr("checked", false);
				});
	});

	//显示新增商品
	function showSelectProduct() {
		var data;
		var html = "";
		document.getElementById("selectProduct").style.display = "";
		for (var i = 0; i < selectPrds.length; i++) {
			data = selectPrds[i].split("_");
			for (var j = 0; j < data.lenght; j++) {
				if (data[j] == "") {
					data[j] = "  ";
				}
			}
			html += "<tr><td>" + (parseInt(1) + i) + "</td>";
			html += "<td>" + data[0] + "</td>";
			html += "<td>" + data[1] + "</td>";
			html += "<td>" + data[2] + "</td>";
			html += "<td>" + data[3] + "</td>";
			html += "<td>" + data[4] + "</td>";
			html += "<td>" + data[5] + "</td>";
			if(typeof(data[6]) == 'undefined')
				{
					html += "<td><input type='text' class='iput_t w100' onchange=\"checkCnt(this,"
						+ data[5] + ");\"></td>";
					html += "<td><input type='text' class='iput_t w100'></td>";
					html += "<td><input type='text' class='iput_t w100'></td>";
				}
			else
				{
					html += "<td><input type='text' value='"+data[6]+"' class='iput_t w100' onchange=\"checkCnt(this,"
						+ data[5] + ");\"></td>";
					html += "<td><input type='text' value='"+data[7]+"' class='iput_t w100'></td>";
					html += "<td><input type='text' value='"+data[8]+"' class='iput_t w100'></td>";
				}
			
			html += "<td><input type='button' onclick=\"removeVal(this);\" class='btn_l' value='删除'/></td></tr>";
		}
		$("#tbody").html(html);
	}

	//从出库表删除商品
	function removeVal(obj) {
		 $(obj).parent().parent().remove();
		 //重新构造数组
		 initSelectPrds();
		 //刷新表格
		//showSelectProduct();
	}
	
	//重新构造数组
	function initSelectPrds() {
		 selectPrds = [];
		 excludeId = [];
		 $("#selectProduct tr").each(function (){
				var fkPrdId = $(this).find("td:eq(1)").html();
				var prdName = $(this).find("td:eq(2)").html();
				var cateName = $(this).find("td:eq(3)").html();
				var prdSpec = $(this).find("td:eq(4)").html();
				var unitName = $(this).find("td:eq(5)").html();
				var stgCnt = $(this).find("td:eq(6)").html();
				var outStgCut = $(this).find("td:eq(7)").find("input").val();
				var signAture = $(this).find("td:eq(8)").find("input").val();
				var comments = $(this).find("td:eq(9)").find("input").val();
				selectPrds.push(fkPrdId + " _" + prdName + "_"
						+ cateName + "_" + prdSpec + "_"
						+ unitName + "_" + stgCnt +"_"+outStgCut+"_"+signAture+"_"+comments);
				excludeId.push(pkPrdId);
			});
	 }
	
	//添加商品到出库表
	function addSelectGoods() {
		//获取当前列表已经选中的id值
		$("#excludeId").val(excludeId.join());
		initTable("goodsOutForm");
		$('#addSelectGoods').window('open');
	}

	//检测出库数量合法性
	function checkCnt(obj, inStgCut) {
		if (inStgCut == 0) {
			alertError("当前商品库存为零！无法出库请删除");
			$(obj).val("");
			retrun;
		}
		var v = $(obj).val();
		if ($.trim(v) != "")//去空格
		{
			if (isNaN(v) || (v.indexOf(".") > -1)) {
				alertError("请输入整数");
				$(obj).val("");
				$(obj)[0].focus();
				return;
			}
		} else {
			$(obj).val("0");
		}
		if (v < 0) {
			alertError("请输入正数");
			$(obj).val("");
			$(obj)[0].focus();
			return;
		}
		if (inStgCut < v) {
			alertError("出库数量超过库存，请修改");
			$(obj).val("");
			$(obj)[0].focus();
			return;
		}
	}

	//出库
	function stockGoodsOut() {
		//出库前验证信息
		if ($("#fkAttFile").val() == "") {
			alertError("出库前必须上传出库附件");
			return;
		}
		var isOk = true;
		$("#selectProduct tr").each(
				function() {
					var outStgCut = $(this).find("td:eq(7)").find("input").val();
					var signAture = $(this).find("td:eq(8)").find("input").val();
					outStgCut = $.trim(outStgCut);
					signAture = $.trim(signAture);
					if (outStgCut == null || outStgCut == "" || outStgCut == 0
							|| signAture == "") {
						isOk = false;
					}
				});
		if (!isOk) {
			alertError("请填写出货数量和签收人");
			return;
		}
		var contents = "";
		$("#selectProduct tr").each(function() {
				//商品id
				var prdId = $(this).find("td:eq(1)").html();
				//出货数量
				var outStgCut = $(this).find("td:eq(7)").find("input").val();
				//签收人
				var signAture = $(this).find("td:eq(8)").find("input").val();
				//备注
				var comments = $(this).find("td:eq(9)").find("input").val();
				//库存数量
				var stgCnt = $(this).find("td:eq(6)").html();
				contents += prdId + "_" + outStgCut + "_"
						+ signAture + "_" + comments + "_" + stgCnt + "|";
				});
		if (contents == "") {
			alertError("请添加出库商品");
			return;
		}
		if (isOk) {
			$("#contents").val(contents);
			$.ajax({
				url : "${basePath}StockGoodsOut/doStockGoodsOut.shtml",
				data : $("#stockGoodsOut").serialize(),
				dataType : "text",
				type : "post",
				async : false,
				success : function(result) {
					if (result == 1) {
						//出库成功后跳转
						window.location.href = "${basePath}StockGoodsOut/toStockGoodsOut.shtml";
					}
					if (result == 0) {
						alertError("出库失败，请检查网络重新出库");
					}
				},
				error : function(XMLHttpRequest) {
					ajaxError(XMLHttpRequest);
				}
			});
		}
	}
</SCRIPT>
	</head>
<body class="bg">
<div class="content m_auto">
	<div class="content_l mt10">
    	<ul>
        	 <shiro:hasPermission name="StockGoodsIn/toStock_goodsIn.shtml">
       		<li><a href="${basePath}StockGoodsIn/toStock_goodsIn.shtml"><i class="nav_icon_b"></i><br>商品入库</a></li>
			</shiro:hasPermission>
		<shiro:hasPermission name="StockQuery/toStockQuery.shtml">
			<li><a href="${basePath}StockQuery/toStockQuery.shtml"><i class="nav_icon_b"></i><br>库存查询</a></li>
			</shiro:hasPermission>
		<shiro:hasPermission name="StockGoodsOut/toStockGoodsOut.shtml">
			<li class="content_hover"><a href="${basePath}StockGoodsOut/toStockGoodsOut.shtml"><i class="nav_icon_b"></i><br>商品出库</a></li>
			</shiro:hasPermission>
		<shiro:hasPermission name="StockTaking/toStockTaking.shtml">
			<li><a href="${basePath}StockTaking/toStockTaking.shtml"><i class="nav_icon_a"></i><br>库存盘点</a></li>
            </shiro:hasPermission>
		<shiro:hasPermission name="StockCorrect/toStockCorrect.shtml">
            <li><a href="${basePath}StockCorrect/toStockCorrect.shtml"><i class="nav_icon_f"></i><br>库存调整</a></li>
        </shiro:hasPermission>
        </ul>
    </div>
    <div class="content_r mt10">
    	<div class="p20">
    	<div class="file_single_dl f14 fixed">
    	    <dl class="fixed"  >
            	<dd><label> 商品出库清单</label></dd>
            	  
            </dl>
            <hr>
       		 <dl class="fixed"  >
                <dd > <label>出库单编号：</label>${stockId}</dd>
                <dd><label>制单人：</label>${userName}</dd>
            </dl>
            <hr>
        	<dl class="fixed" style="overflow:hidden">
            	<dd><label>出货仓库：</label>${branName}
                </dd>
                
                <dd><label>制单时间：</label>${createTime}</dd>
            </dl>
            <hr>
             <dl class="fixed"  >
             <label><h1>出库单附件上传：</h1></label>
                <dd>
					<div class="upload_box">
						<input type="text" id="ui-upload-filepathtxt" class="iput_t fl">
						<span id="ui-upload-holder fr"> 
						<input type="button" class="btn" value="上传" id="ui-upload-txt" onclick="uploadAttachFile();"> 
						<input type="file"id="ui-upload-input" name="file" onchange="fileName()">
						</span> <input type="button" class="btn fl ml10" value="浏览">
					</div>
				</dd>
            </dl>
             
        </div>
             <div id="scrollTable" style="width:1100px">
            <table class="table">
                <col width="80px"></col>
                <col width="130px"></col>
                <col width="80px"></col>
                <col width="80px"></col>
                <col width="80px"></col>
                <col width="80px"></col>
                <col width="80px"></col>
                <col width="130px"></col>
                <col width="130px"></col>
                <col width="130px"></col>
                <col></col>
                <tbody>
                    <tr>
                       	  <th>序号</th>
                          <th>商品编号</th>
                          <th>商品名称</th>
                          <th>商品分类</th>
                          <th>规格</th>
                          <th>单位</th>
                          <th>库存数量</th> 
                          <th>出货数量</th> 
                          <th>签收人</th> 
                          <th>备注</th> 
                          <th>操作</th> 
                    </tr>
                </tbody>
            </table>
			<div>
            <table class="table" id="selectProduct" >
				<col width="80px"></col>
                <col width="130px"></col>
                <col width="80px"></col>
                <col width="80px"></col>
                <col width="80px"></col>
                <col width="80px"></col>
                <col width="80px"></col>
                <col width="130px"></col>
                <col width="130px"></col>
                <col width="130px"></col>
                <col></col>
                <tbody id="tbody">
                  
                </tbody>
            </table>
            </div>
        </div>
                    <!----底部按钮----->
                    <div class="btm_btn mt10">
                            <dl>
                            	<dd><input class="btn" type="button" value="新增" onClick="addSelectGoods();"></dd>
                                <dd><input class="btn" type="button" value="出库" onclick="stockGoodsOut();"></dd>
                                <dd><input class="btn" type="button" value="打印" ></dd>
                                 <dd><input class="btn" type="button" value="返回" onClick="javascript:history.go(-1)"></dd>
                            </dl>
                    </div>
                    <!----底部按钮----->
    	</div>
	</div>
</div>

	<form action="${basePath}StockGoodsOut/doStockGoodsOut.shtml" id="stockGoodsOut" method="post">
		<input type="hidden" name="pkOutstgId" id="pkOutstgId" value="${stockId}">
		<input type="hidden" name="fkAttFile" id="fkAttFile">
		<input type="hidden" name="fkBranId" id="fkBranId" value="${storeId}">
		<input type="hidden" name="modiBy" id="modiBy" value="${usrId}">
		<input type="hidden" name="contents" id="contents">
	</form>
	
	<form action="${basePath}StockQuery/findProductListForStock.shtml" id="goodsOutForm" method="post">
		<input type="hidden" name="pageNo" value="1">
		<input type="hidden" name="pageSize" value="8">
		<input type="hidden" name="pkPrdId" id="pkPrdId">
		<input type="hidden" name="prdName" id="prdName">
		<input type="hidden" name="selectId" id="selectId">
		<input type="hidden" name="excludeId" id="excludeId" />
		<input type="hidden" name="resverseTypes" id="resverseTypes"/>
		<input type="hidden" name="fkBranId" id="fkBranId2" value="${storeId}">
	</form>
	
	<form action="${basePath}StockQuery/findProductListForStock.shtml" id="allstockQueryForm" method="post">
		<input type="hidden" name="pageNo" value="1">
		<input type="hidden" name="pageSize" value="8">
		<input type="hidden" name="pkPrdId" id="pkPrdId2">
		<input type="hidden" name="prdName" id="prdName2">
		<input type="hidden" name="excludeId" id="excludeId2" />
		<input type="hidden" name="resverseTypes" id="resverseTypes2"/>
		<input type="hidden" name="fkBranId" id="fkBranId3" value="${storeId}">
	</form>
	
<!---弹出层 成员信息编w辑--->
<div id="addSelectGoods" class="easyui-window" title="新增出库商品" data-options="modal:true,closed:true,iconCls:'icon-save'" style="width: 1224px; height: 500px; position: relative;">
			<div class="content m_auto">
					<div class="p20">
						<div class="file_single_dl f14 fixed">
							<dl class="fixed" style="overflow: hidden">
								<dd>
									<label>商品编号：</label><input type="text" class="iput_t w200"
										id="pkPrdIdValue">
								</dd>
								<dd>
									<label>商品名称：</label><input type="text" class="iput_t w200"
										id="prdNameValue">
								</dd>
								<dd>
									<input type="button" class="btn fr" value="查询"
										onclick="select1('goodsOutForm');">
								</dd>
							</dl>
						</div>

						<div class="tab_normal mt10" style="height: 200px;">
							<ul class="fixed" id="tab_a"></ul>
							<div class="payment_l tc"
								style="height: 342px;width: 180px !important; ">
								<div  class="ztree m10" id="sptree" style="overflow-y: auto;width: 160px; height: 315px;"></div>
								</div>
							<ul class="fixed" id="tab_conbox_a"
								style="height: 340px !important; width: 1200px;">
								<li class="p10 " style="margin-left: 200px">
									<table class="table" id="goodsOutTable">
										<tr>
											<th><input name='chkItemAll' type="checkbox" id="selectAll"/></th>
											<th>序号</th>
											<th>商品编号</th>
											<th>商品名称</th>
											<th>商品分类</th>
											<th>规格</th>
											<th>计量单位</th>
											<th>库存数量</th>
										</tr>
									</table> 
									<input class="btn mt10 fl" type="button" value="确定" id="addGoods">
									<input class="btn mt10 ml10 fl" type="button" value="返回" onClick="$('#addSelectGoods').window('close')">									
									<!----翻页----->
									<div class="page fr m10" id="goodsOutFoot"></div> 
									<!----翻页----->
								</li>
							</ul>
					</div>
				</div>
			</div>
		</div>
		
</body>
</html>